package com.topisv.tms.task;

import java.util.concurrent.BlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topisv.tms.entity.task.MdSendOutTask;
import com.topisv.tms.service.md.MdSendOutTaskService;
import com.topisv.tms.utils.enums.TaskStatus;

public class MdSendOutTaskWorker extends Thread {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private BlockingQueue<MdSendOutTask> tasks;
	private MdSendOutTaskService mdSendOutTaskService;

	public MdSendOutTaskWorker(BlockingQueue<MdSendOutTask> tasks, MdSendOutTaskService mdSendOutTaskService) {
		this.tasks = tasks;
		this.mdSendOutTaskService = mdSendOutTaskService;
	}

	@Override
	public void run() {
		while (true) {
			MdSendOutTask task = null;
			try {
				task = tasks.take();
				if (task != null) {
					mdSendOutTaskService.dealTask(task);
					logger.info("{} send to md finish",task.getCustomerOrderNo());
				}
			} catch (Exception e) {
				logger.error("MdSendOutTaskWorker case some error.", e);
				if (task != null) {
					if (task.getDealCount() >= 5) {
						task.setDealStatus(TaskStatus.FAIL.getStatus());
					} else {
						task.setDealStatus(TaskStatus.UNHAND.getStatus());
						task.setDealIp(null);
					}
					mdSendOutTaskService.save(task);
				}
			}
		}
	}

}
